package aliyun

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"strconv"
	"time"

	"github.com/astaxie/beego/logs"
)

func postTTS(appkey string, token string, text string, audioSaveFile string) error {
	/**
	 * 设置HTTPS POST请求
	 * 1.使用HTTPS协议
	 * 2.语音合成服务域名：nls-gateway.cn-shanghai.aliyuncs.com
	 * 3.语音合成接口请求路径：/stream/v1/tts
	 * 4.设置必须请求参数：appkey、token、text、format、sample_rate
	 * 5.设置可选请求参数：voice、volume、speech_rate、pitch_rate
	 */
	var url string = "https://nls-gateway.cn-shanghai.aliyuncs.com/stream/v1/tts"
	bodyContent := make(map[string]interface{})
	bodyContent["appkey"] = appkey
	bodyContent["text"] = text
	bodyContent["token"] = token
	bodyContent["format"] = "wav"
	bodyContent["sample_rate"] = 8000
	// voice 发音人，可选，默认是xiaoyun
	// bodyContent["voice"] = "xiaoyun"
	// volume 音量，范围是0~100，可选，默认50
	// bodyContent["volume"] = 50
	// speech_rate 语速，范围是-500~500，可选，默认是0
	// bodyContent["speech_rate"] = 0
	// pitch_rate 语调，范围是-500~500，可选，默认是0
	// bodyContent["pitch_rate"] = 0
	bodyJson, err := json.Marshal(bodyContent)
	if err != nil {
		logs.Error("file:%v json marshal failed:%v", audioSaveFile, err)
		return err
	}
	fmt.Println(string(bodyJson))
	/**
	 * 发送HTTPS POST请求，处理服务端的响应
	 */

	start := time.Now()
	logs.Debug("[%v] start send :%v:%v", audioSaveFile, start.Format("2006-01-02 15:04:04"), start.Nanosecond())
	response, err := http.Post(url, "application/json;charset=utf-8", bytes.NewBuffer([]byte(bodyJson)))
	if err != nil {
		logs.Error("audioSaveFile:%v Post failed:%v", audioSaveFile, err)
		return err
	}

	defer response.Body.Close()
	contentType := response.Header.Get("Content-Type")
	body, _ := ioutil.ReadAll(response.Body)

	if "audio/mpeg" == contentType {
		file, _ := os.Create(audioSaveFile)
		defer file.Close()
		file.Write([]byte(body))

		end := time.Now()
		cost := end.Sub(start)
		logs.Debug("audioSaveFile %v request succeed!cost:%v", audioSaveFile, cost)

	} else {
		// ContentType 为 null 或者为 "application/json"
		statusCode := response.StatusCode
		logs.Debug("[%v]The HTTP statusCode:%v ", audioSaveFile, strconv.Itoa(statusCode))
		logs.Debug("[%v]The POST request failed: %v", audioSaveFile, string(body))

		return errors.New(string(body))
	}

	return nil
}
